<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

const props = defineProps({
  zoom: {
    type: Number,
    default: 11,
  },
  center: {
    type: Array,
    default: function () {
      return [];
    },
  },
});

let map = null;
let containerRef = ref(null);

let positionList = [];
let markerList = [];
const isLoaded = ref(true);
watch(
  isLoaded,
  (newValue, oldValue) => {
    if ((newValue === true) & (oldValue === false)) {
      addMaker();
    } else if (newValue === false) {
      if (map !== null) isLoaded.value = true;
    }
  },
  { immediate: true }
);
//点标记显示内容
const markerContent = `<div class="custom-content-marker">
<img src="//zxyt-wryyyyy.oss-cn-beijing.aliyuncs.com/f552af19-71e9-4d6c-a705-f4eb5765308e.png">`;

onMounted(() => {
  AMapLoader.load({
    key: "839ea810896ab1c878a741c82569d46d", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map = new AMap.Map(containerRef.value, {
        // 设置地图容器id
        viewMode: "2D", // 是否为3D地图模式
        zoom: props.zoom, // 初始化地图级别
        center:
          props.center.length === 0 ? [116.397428, 39.90923] : props.center, // 初始化地图中心点位置
        mapStyle: "amap://styles/darkblue",
      });
      isLoaded.value = true;
    })
    .catch((e) => {
      console.log(e);
    });
});

onUnmounted(() => {
  map?.destroy();
});

const changeCenter = (area) => {
  map.setCenter(area);
};

const addPosition = (positions) => {
  // isLoaded 变为true，只能是因为要添加新的坐标
  isLoaded.value = false;
  positionList = positions.slice();
};
const addMaker = () => {
  map.remove(markerList);
  markerList.splice(0, markerList.length);
  for (let i = 0; i < positionList.length; i++) {
    let t = positionList[i].split(" ");
    const maker = new AMap.Marker({
      position: new AMap.LngLat(t[0], t[1]),
      content: markerContent,
      offset: new AMap.Pixel(-13, -30),
      title: "污水厂",
    });
    markerList.push(maker);
  }
  map.add(markerList);
};

defineExpose({
  changeCenter,
  addPosition,
});
</script>

<template>
  <div ref="containerRef" id="container"></div>
</template>

<style lang="scss" scoped>
#container {
  width: 100%;
  height: 100%;
}
.custom-content-marker {
  position: relative;
  width: 25px;
  height: 34px;
  background-color: rgba(0, 0, 0, 0);
}
.custom-content-marker img {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0);
}
</style>